package com.icee.myth.common.encoder;

import com.icee.myth.common.protobufMessage.ProtobufMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

import static io.netty.buffer.Unpooled.EMPTY_BUFFER;

/**
 * TypeLengthFieldProtobufEncoder用于编码除GW与Map间的服务器间消息
 *
 * @author chencheng
 */
public class Type4BytesLengthFieldProtobufEncoder extends AbsProtobufEncoder {

    public Type4BytesLengthFieldProtobufEncoder() {
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        if (null == msg) {
            throw new Exception("Type4BytesLengthFieldProtobufEncoder msg is null");
        }
        if (msg instanceof ProtobufMessage) {
            ByteBuf sendBuf = super.encodeProtobufMessage2(ctx.channel(), (ProtobufMessage) msg);
            if (null != sendBuf && !sendBuf.equals(EMPTY_BUFFER)) {
                out.writeBytes(sendBuf);
            } else {
                throw new Exception("Type4BytesLengthFieldProtobufEncoder sendBuf is null or EMPTY_BUFFER");
            }
        } else {
            throw new Exception("Type4BytesLengthFieldProtobufEncoder msg unknow");
        }
    }

}
